package com.huawei.aiosproj.view;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.widget.Button;
import android.widget.Toast;

import com.huawei.aiosproj.R;

import java.util.Calendar;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {

    // 权限请求码
    private static final int CALL_PERMISSION_CODE = 101;
    private static final int CALENDAR_PERMISSION_CODE = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 拨号按钮事件
        Button btnCall = findViewById(R.id.btn_call);
        btnCall.setOnClickListener(v -> {
            if (checkCallPermission()) {
                makePhoneCall();
            }
        });

        // 日历按钮事件
        Button btnCalendar = findViewById(R.id.btn_calendar);
        btnCalendar.setOnClickListener(v -> {
            if (checkCalendarPermission()) {
                addCalendarEvent();
            }
        });
    }

    // 检查拨号权限
    private boolean checkCallPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    CALL_PERMISSION_CODE);
            return false;
        }
        return true;
    }

    // 检查日历权限
    private boolean checkCalendarPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_CALENDAR},
                    CALENDAR_PERMISSION_CODE);
            return false;
        }
        return true;
    }

    // 拨打电话实现
    private void makePhoneCall() {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:10086"));
            startActivity(callIntent);
        } catch (SecurityException e) {
            Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
        }
    }

    // 添加日历事件实现
    private void addCalendarEvent() {
        try {
            // 设置会议时间（当前时间+1小时开始，持续1小时）
            Calendar startTime = Calendar.getInstance();
            startTime.add(Calendar.HOUR, 1);
            long startMillis = startTime.getTimeInMillis();

            Calendar endTime = Calendar.getInstance();
            endTime.add(Calendar.HOUR, 2);
            long endMillis = endTime.getTimeInMillis();

            // 创建事件
            ContentValues event = new ContentValues();
            event.put(CalendarContract.Events.CALENDAR_ID, 1); // 默认日历
            event.put(CalendarContract.Events.TITLE, "团队周会");
            event.put(CalendarContract.Events.DESCRIPTION, "每周项目进度同步会议");
            event.put(CalendarContract.Events.EVENT_LOCATION, "会议室A");
            event.put(CalendarContract.Events.DTSTART, startMillis);
            event.put(CalendarContract.Events.DTEND, endMillis);
            event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            event.put(CalendarContract.Events.HAS_ALARM, 1); // 设置提醒

            // 插入事件
            ContentResolver cr = getContentResolver();
            Uri eventUri = cr.insert(CalendarContract.Events.CONTENT_URI, event);

            if (eventUri != null) {
                // 添加提醒（提前10分钟）
                long eventID = Long.parseLong(eventUri.getLastPathSegment());
                ContentValues reminder = new ContentValues();
                reminder.put(CalendarContract.Reminders.EVENT_ID, eventID);
                reminder.put(CalendarContract.Reminders.MINUTES, 10);
                reminder.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
                cr.insert(CalendarContract.Reminders.CONTENT_URI, reminder);

                Toast.makeText(this, "会议已添加到日历", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "添加失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // 权限回调处理
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CALL_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                makePhoneCall();
            } else {
                Toast.makeText(this, "拨号权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == CALENDAR_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                addCalendarEvent();
            } else {
                Toast.makeText(this, "日历权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
